<?php
/**
 * _.class - tools
 *
 * @version:	0.1a
 * @package:	global
 * @author:	alex_ez
 * @created:	16.02.2009 15:02:27
 *
 * @copyright:	(c) 2009 alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved.
 */



final class _
{
	static public function parse_args($args, $defaults = false) {
		$r = array();

		if ( is_object( $args ) )
			$r = get_object_vars( $args );
		elseif ( is_array( $args ) )
			$r =& $args;
		else
			parse_str( $args, $r );

		if(is_array( $defaults))
			return array_merge( $defaults, $r );

		return $r;
	}

	static public function extract_args($args, $defaults) {
        $rslt = array();

        $options = _::parse_args($args, $defaults);

        if(is_array($defaults))
            foreach(array_keys($defaults) as $key)
                $rslt[$key] = $options[$key];

        return $rslt;
    }
        
	static public function pick( )
	{
		$_A = func_get_args();
		if( sizeof( $_A ) == 1 && is_array( reset( $_A ) ) ) $_A = reset( $_A );
		
		foreach( array_keys( $_A ) as $k )
		if( isset( $_A[$k] )
		 && !is_null( $_A[$k] ) )
			return $_A[$k];
		
		return null;
	}
	
	static public function pickAny( )
	{
		$_A = func_get_args();
		if( sizeof( $_A ) < 1 ) return null;
		
		return $_A[ rand( 0, sizeof( $_A )-1 ) ];
	}
	
	static public function plural( )
	{
		$args = func_get_args( );
		$f = array_shift( $args );
		if( !is_array( $f ) )
		{
			$f = array( $f );
			while( !is_numeric( reset( $args ) ) && !empty( $args ) )
				$f[] = array_shift( $args );
		}
		$n = array_shift( $args );
		
		$pluralForms = array(
		'ru' => array(
			'nplurals' => 3,
			'plural' => '( (n%10)==1 && (n%100)!=11 ) ? 0 : ( n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2 )'
			),
		);
		
		$l = 'ru';
		$ff = create_function( '$n', 'return '.str_replace( 'n', '$n', $pluralForms[$l]['plural'] ).';' );
		$m = $ff( $n );
		$r = !isset( $f[ $m ] ) ? $f[ $m ] : reset( $f );
		
		return $f[ $m ];
	}

	static public function subst( $pattern, $fields, $wrapper = '{%s}' )
	{
		return str_replace(
				array_map( create_function( '$a', 'return sprintf("'.$wrapper.'",$a);' ), array_keys( $fields ) ),
				array_values( $fields ),
				$pattern );
	}
}

?>